//
// Forward declare functions
//
var getAccountIds;
var getStatementsUrl;
var getTransactionsUrl;


function handleAccountsPage(page)
{
    var accountIds = getAccountIds(document);
    
    debugLog('accountIds = ' + accountIds);

    for (var index=0; index < accountIds.length; index++)
    {
        // Open a new browser window for each account to handle downloading statements for that account
        var statementsUrl = getStatementsUrl(accountIds[index]);
        debugLog('opening window at "' + statementsUrl +'"');
        window.open(statementsUrl);

        // Open a new browser window for each account to handle downloading transactions for that account
        var transactionsUrl = getTransactionsUrl(accountIds[index]);
        debugLog('opening window at "' + transactionsUrl +'"');
        window.open(transactionsUrl);
    };
}

function getStatementsUrl(accountId)
{
    return STATEMENTS_DOWNLOAD_PAGE_BASE_URL + '?' + QUERYPARAMETER_ACCOUNT_IDENTITIFIER + '=' + accountId;
}

function getTransactionsUrl(accountId)
{
    return TRANSACTIONS_DOWNLOAD_BASE_URL + '?' + QUERYPARAMETER_ACCOUNT_IDENTITIFIER + '=' + accountId;
}

//
// Finds all account idenitifiers on the given document
//
function getAccountIds(doc)
{
    // Each account has a static, unique identifier associated with it.
    // This identifier appears in many of the hyperlinks (anchors)
    // on this page in the form of a URL query parameter.
    // e.g.  https://stmts.chase.com/stmtslist?AI=169999999
    // In the above example the query parameter name is "AI" and its
    // value is "169999999".
    // This value will henceforth be referred to as the "account ID"

    var anchors = doc.getElementsByTagName('a');
    var accountIds = new Array();
    var tempIds = new Array();
    
    tempIds = getQueryParameterValueFromMultipleAnchors(anchors, QUERYPARAMETER_ACCOUNT_IDENTITIFIER);
    tempIds = tempIds.getUnique();
    
    debugLog('tempIds = ' + tempIds);

    for (var index=0; index < tempIds.length; index++)
    {
        if ('' != tempIds[index])
        {
            accountIds.push(tempIds[index]);
        }
    };
    
    return accountIds;
}
